package com.seckill.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.seckill.commons.Constants;
import com.seckill.orders.mapper.OrdersMapper;
import com.seckill.orders.model.Orders;
import com.seckill.orders.service.OrderService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.Date;

@Service
public class OrdersServiceImpl implements OrderService {
    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public int addOrder(Orders orders) {

        try {
            orders.setStatus(1);
            orders.setCreateTime(new Date());
            orders.setBuyNum(1);
            orders.setOrderMoney(orders.getBuyPrice().multiply(new BigDecimal(orders.getBuyNum())));
            //插入数据到数据，这里可能会抛出异常DuplicateKeyException，表示违反数据库的唯一约束异常
            ordersMapper.insert(orders);
            String key=Constants.ORDERS_RESULT+orders.getGoodsId()+":"+orders.getUid();
            String value= JSONObject.toJSONString(orders);
            //使用统一Key前缀+商品Id+用户Id作为Key
            //使用订单的Json作为value
            //指定Key的超时时间为5分钟
            //将订单结果存入Redis用于通知前端下单成功
            stringRedisTemplate.opsForValue().set(key,value, Duration.ofSeconds(60*5));
        } catch (DuplicateKeyException e) {
            //进入这里表示违反唯一约束，用户Id和商品Id的组合已经存在，证明这条消息是重复消息
            return 0;
        }
        return 0;
    }

    @Override
    public Orders getOrderResult(Integer goodsId, Integer uid) {
        String orderStr= stringRedisTemplate.opsForValue().get(Constants.ORDERS_RESULT+goodsId+":"+uid);
        //进入if表示没有获取到订单结果
        if(orderStr==null){
            return null;
        }
        return JSONObject.parseObject(orderStr,Orders.class);
    }
}
